//
//  MTGroupImageDownLoadTool.swift
//  MT
//
//  Created by ooops on 2020/1/3.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Messages
import RxSwift
import RxCocoa
import Kingfisher

class MTGroupImageDownLoadTool: NSObject {
    
    class func downImage(_ group: JMSGGroup, complete: @escaping (_ images: [UIImage]) -> Swift.Void) {
        group.asyncUsers { (users) in
            if let jusers = users {
                
                var images: [UIImage] = []
                
                let count = (jusers.count > 4 ? 4 : jusers.count)
                
                for _ in 0..<count {
                    images.append(UIImage(named: defaultPlaceholderIcon60x60)!)
                }
                
                var obseArray: [Observable<UIImage>] = []
                
                if jusers.count == 0 {
                    complete([])
                    return
                }
                
                for (i, user) in jusers.enumerated() {
                    if i == count {
                        break
                    }
                    obseArray.append(self.rx_downloadImage(withUSER: user))
                    
                }
                if obseArray.count == 0 {
                    complete(images)
                    return
                }
                _ = Observable.zip(obseArray).subscribe { (element) in
                    if let s = element.element {
                        complete(s)
                    }
                }.disposed(by: globalDisposedBag)
            }
        }
    }
    
    class func rx_downloadImage(withUSER user: JMSGUser?) -> Observable<UIImage> {
            return Observable.create({ observer -> Disposable in
                user?.thumbAvatarData({ (data, id, error) in
                    if error != nil {
                        if let u = user?.avatar, let url = URL(string: u) {
                            KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: u, options: [.onlyFromCache]) { (result: Result<KFCrossPlatformImage?, KingfisherError>) in
                                switch result {
                                case .success(let image):
                                    if image == nil {
                                        ImageDownloader.default.downloadImage(with: url, options: KingfisherParsedOptionsInfo(.none)) { (result: Result<ImageLoadingResult, KingfisherError>) in
                                            switch result {
                                            case .success(let imageLoading):
                                                /// cache Image 下载都下载了, 顺便缓存一下吧
                                                KingfisherManager.shared.cache.store(imageLoading.image, forKey: u)
                                                observer.onNext(imageLoading.image)
                                                observer.onCompleted()
                                            case .failure(let error):
                                                observer.onError(error)
                                            }
                                        }
                                    } else {
                                        observer.onNext(image!)
                                        observer.onCompleted()
                                    }
                                case .failure(_):
                                    ImageDownloader.default.downloadImage(with: url, options: KingfisherParsedOptionsInfo(.none)) { (result: Result<ImageLoadingResult, KingfisherError>) in
                                        switch result {
                                        case .success(let imageLoading):
                                            /// cache Image 下载都下载了, 顺便缓存一下吧
                                            KingfisherManager.shared.cache.store(imageLoading.image, forKey: u)
                                            observer.onNext(imageLoading.image)
                                            observer.onCompleted()
                                        case .failure(let error):
                                            observer.onError(error)
                                        }
                                    }
                                }
                            }
                        } else {
                            observer.onError(error!)
                        }
                    } else if let data = data {
                        if let image = UIImage(data: data) {
                            observer.onNext(image)
                            observer.onCompleted()
                        }
                    }
                })
                return Disposables.create()
            })
        }
    
}

extension JMSGGroup {
    
    
    /// 获取所有群组用户列表信息
    func asyncUsers(complete: @escaping (_ users: [JMSGUser?]?) -> Swift.Void) {
        self.memberInfoList { (result, error) in
            if error == nil {
                if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                    let users = userInfos.map { (info) -> JMSGUser? in
                        return info.user
                    }
                    complete(users)
                }
            } else {
                complete(nil)
            }
        }
    }
    
}
